package com.study.spmongodb.wwj.thread2.char13;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/8 22:09
 */
public class ProducerTread extends Thread {
    private final MessageQueue messageQueue;

    private final static Random random = new Random(System.currentTimeMillis());

    private final static AtomicInteger counter = new AtomicInteger(0);

    public ProducerTread(MessageQueue messageQueue, int seq) {
        super("producer-" + seq);
        this.messageQueue = messageQueue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                final Message message = new Message("Message-" + counter.getAndIncrement());
                messageQueue.put(message);
                System.out.println(Thread.currentThread().getName() + "put message:" + message.getData());
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }
    }
}
